package com.zc.common.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhangchi9 on 2016/12/6.
 */
public class StringUtils {
    private static final Pattern KVP_PATTERN = Pattern.compile("([_.a-zA-Z0-9][-_.a-zA-Z0-9]*)[=](.*)"); //key value pair pattern.

    public static String getQueryStringValue(String qs, String key) {
        Map<String, String> map = StringUtils.parseQueryString(qs);
        return map.get(key);
    }
    public static Map<String, String> parseQueryString(String qs)
    {
        if( qs == null || qs.length() == 0 )
            return new HashMap<String, String>();
        return parseKeyValuePair(qs, "\\&");
    }
    private static Map<String, String> parseKeyValuePair(String str, String itemSeparator)
    {
        String[] tmp = str.split(itemSeparator);
        Map<String, String> map = new HashMap<String, String>(tmp.length);
        for(int i=0;i<tmp.length;i++)
        {
            Matcher matcher = KVP_PATTERN.matcher(tmp[i]);
            if( matcher.matches() == false )
                continue;
            map.put(matcher.group(1), matcher.group(2));
        }
        return map;
    }
}
